package main

import (
	"gopkg.in/alecthomas/kingpin.v2"
	"google.golang.org/grpc"
	"golang.org/x/net/context"
	"encoding/json"
	"os"
	"fmt"
	"block_proto"
)

func blockClient(address string, service string, rpcname string, jsonreq string)  {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		fmt.Errorf("dial failed. err: [%v]\n", err)
		return
	}
	switch service {
	case "server":
		client := block_proto.NewBlockNodeClient(conn)
		switch rpcname {
		case "command":
			request := &block_proto.CommandRequest{}
			err = json.Unmarshal([]byte(jsonreq), request)
			fmt.Println(client.Command(context.Background(), request))
		}
	default:
		fmt.Printf("invalid service[%v]\n", service)
	}
}

func blockClientExample() string {
	return `block_client example:
  ./client server command '{"command": "timeslice"}'
  `
}

func main() {
	kingpin.HelpFlag.Short('h')
	address := kingpin.Flag("address", "服务地址").Short('a').String()
	service := kingpin.Arg("service", "服务, [server]").Required().String()
	rpcname := kingpin.Arg("rpcname", "方法, [command]").Required().String()
	jsonreq := kingpin.Arg("jsonreq", "请求, json格式, '{\"command\": \"pprofmem\"}'").Required().String()

	if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
		kingpin.Usage()
		fmt.Println(blockClientExample())
		return
	}

	kingpin.Parse()

	if *address == "" {
		switch *service {
		case "server":
			*address = "127.0.0.1:21630"
		}
	}

	blockClient(*address, *service, *rpcname, *jsonreq)
}